#The Apps.
#!bash /usr/bin/python3 
import os
import sys
import tkinter as tk
import json
import time
from tkinter import simpledialog
def firstopen(password):
    with open("config.txt", "w") as f:
            f.write(password)
def cheak():
      if os.path.exists("config.txt"):
          print("读取config!")
          with open("config.txt", "r") as f:
              password = f.read().strip()
          return password
      else:
           print("第一次运行!")
           root= tk.Tk()
           root.withdraw()
           passwords = simpledialog.askstring("Password", "Enter a password:")
           os.system("curl https://www.xuanyiy.cn/logined/password.txt -o password.txt")
           with open("password.txt", "r") as f:
                password = f.read().strip()
                if password == passwords:
                        firstopen(passwords)
                        return True
                else:
                        tk.messagebox.showerror("Error", "Incorrect password. Please try again.")
                        sys.exit(1)
      return False
def read_time_hours():
    try:
        # 从 JSON 文件中读取小时
        with open('time.json', 'r') as f:
            data = json.load(f)
            return data['hours']
    except FileNotFoundError:
        print("未找到时间数据文件")
        return None
def read_time_start():
    try:
        # 从 JSON 文件中读取小时
        with open('time.json', 'r') as f:
            data = json.load(f)
            return data['startrun']
    except FileNotFoundError:
        print("未找到时间数据文件")
        return None
def run():
        os.system("curl https://www.xuanyiy.cn/logined/time.json -o time.json")
        times = read_time_start()
        hours = read_time_hours()
        root = tk.Tk()
        root.withdraw()
        if times is not None:
            if times == time.strftime("%H:%M"):
                tk.messagebox.showinfo("运行", "现在是运行时间!")
                print("现在是运行时间!")
                if hours is not None:
                    tk.messagebox.showinfo("运行", f"将会在: {hours} 小时后关机")
                    print(f"将会在: {hours} 小时后关机")
                    time.sleep(hours * 3600)  # 将小时转换为秒
                    os.system("shutdown /s /t 1")  # 关机命令

                else:
                    tk.messagebox.showerror("Error", "无法读取时间数据")
                    print("无法读取时间数据")
                    sys.exit(1)
            else:
                tk.messagebox.showinfo("运行", "现在不是运行时间!")
                print("现在不是运行时间!")
                os.system("logoff")
        else:
            tk.messagebox.showerror("Error", "无法读取时间数据")
            print("无法读取时间数据")
            sys.exit(1)
            
def main():
    password = cheak()
    if password:
        print("运行!")
        run()
if __name__ == "__main__":
    main()